import Dialog from "../../component/vant/dialog/dialog";
import Toast from "../../component/vant/toast/toast";
const xhUploader = require("../../utils/qiniuUploader.js");
const util = require("../../utils/util.js");
var WxParse = require('../../component/wxParse/wxParse.js');
var app = getApp();
const select_options = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
Page({

    /**
     * 页面的初始数据
     */
    data: {
        downloadUrl: app.api.xh.downloadDomain,
        question_html: app.api.xh.domain,//题干请求域名
        timeCounter: '00:00:00',
        questionCount: 0,
        sections: [],
        if_commit: 1,
        select_options: select_options,
        setInter: '',
        num: 0,
        doneQCount: 0,
        show_status: false,
        files: [],
        picture_list: [],
        file_list: [],
        check_mode: 0,//自批模式
        coach_answer: {},
        // 触摸开始时间
        touchStartTime: 0,
        // 触摸结束时间
        touchEndTime: 0,
        // 最后一次单击事件点击发生时间
        lastTapTime: 0,
        // 单击事件点击后要触发的函数
        lastTapTimeoutFunc: null,
        isIPX: app.globalData.isIPX,
        showSkeleton: true
    },
    // 按钮触摸开始触发的事件
    touchStart: function (e) {
        this.touchStartTime = e.timeStamp
    },

    // 按钮触摸结束触发的事件
    touchEnd: function (e) {
        this.touchEndTime = e.timeStamp
    },
    multipleTap: function (e) {
        var that = this
        // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
        if (that.touchEndTime - that.touchStartTime < 350) {
            // 当前点击的时间
            var currentTime = e.timeStamp
            var lastTapTime = that.lastTapTime
            // 更新最后一次点击时间
            that.lastTapTime = currentTime

            // 如果两次点击时间在300毫秒内，则认为是双击事件
            if (currentTime - lastTapTime >= 300) {
                // 单击事件延时300毫秒执行，这和最初的浏览器的点击300ms延时有点像。
                that.lastTapTimeoutFunc = setTimeout(function () {
                    wx.previewImage({
                        current: e.currentTarget.id, // 当前显示图片的http链接
                        urls: that.data.files // 需要预览的图片http链接列表
                    });
                }, 300);
            }
        }
    },
    //长按删除图片
    longTap: function (e) {
        var page = this;
        if (page.data.if_commit == 2) {
            return false;
        }
        let index = parseInt(e.currentTarget.dataset.index);
        Dialog.confirm({
            title: '提示',
            message: "确定删除图片吗"
        }).then(() => {
            let files = page.data.files,
                picture_list = page.data.picture_list;
            files.map((f, i) => {
                if (i == index) {
                    files.splice(i, 1);
                }
            })
            picture_list.map((p, i) => {
                if (i == index) {
                    picture_list.splice(i, 1);
                }
            })
            page.setData({
                files: files,
                picture_list: picture_list
            })
        });

    },
    jump: function () {
        var page = this;
        wx.redirectTo({
            url: '../coach_result/coach_result?id=' + page.data.coach_id
        })
    },
    submit: function () {
        var page = this,
            sections = page.data.sections;

        var check_done = 1;//判断是否完成所有客观题作答
        var item_list = [];
        var objective_score = 0;//客观题分数
        var has_subjective_question = 1;
        sections.map((item, index) => {
            sections[index].questions.map((q, i) => {
                if (q.category == 'select' || q.category == 'judge') {
                    if (sections[index].questions[i].student_answer == undefined) {
                        check_done = 0;
                    } else {

                        if (sections[index].questions[i].student_answer.length == 0) {
                            check_done = 0;
                        }

                        var if_right = 2;
                        var student_answer = sections[index].questions[i].student_answer;
                        var correct = sections[index].questions[i].correct;

                        //选择题判断作答正确性
                        if (sections[index].questions[i].category == 'select') {
                            //多选题的情况
                            if (sections[index].questions[i].correct.length > 1) {
                                if (util.sortStr(student_answer).join('') == util.sortStr(correct).join('')) {
                                    if_right = 1;
                                }
                                student_answer = student_answer.join('');
                            } else {
                                //单选的情况
                                if (student_answer == correct) {
                                    if_right = 1;
                                }
                            }
                        }
                        //判断题的情况
                        if (sections[index].questions[i].category == 'judge' && student_answer == correct) {
                            if_right = 1;
                        }
                        item_list.push({
                            uuid: sections[index].questions[i].uuid,
                            answer: student_answer,
                            if_right: if_right
                        })
                        objective_score += if_right == 1 ? sections[index].questions[i].score * 1 : 0;
                    }
                }
            })
        });


        //判断是否有主观题
        // 客观题数量
        var objective_question_num = 0;
        sections.map((item, index) => {
            sections[index].questions.map((question, i) => {
                if (question.category == 'select' || question.category == 'judge') {
                    objective_question_num += 1;
                }
            })
        });

        // 是否含有主观题
        if (objective_question_num == page.data.questionCount) {
            has_subjective_question = 0;
        } else {
            has_subjective_question = 1;
        }
        //判断是否有主观题


        if (check_done == 0) {
            Dialog.alert({
                message: '请先完成所有客观题的作答。'
            });
            return false;
        }

        var answer_json = {
            finish: has_subjective_question == 1 ? 0 : 1,
            picture_list: page.data.picture_list,
            score: objective_score + '',
            use_time: page.data.timeCounter + '',
            item_list: item_list
        };

        var param = {
            coach_id: page.data.coach_id,
            answer_json: JSON.stringify(answer_json)
        }

        page.setData({
            coach_answer: {
                item_list: item_list,
                use_time: page.data.timeCounter + '',
                score: objective_score,
                picture_list: page.data.picture_list
            }
        })

        if (has_subjective_question == 1) {
            app.setPageTitle('自批主观题');
            page.setData({
                check_mode: 1
            })
            app.goTop();
        } else {

            var subjective_score = 0;//主观题分数
            sections.map((item, index) => {
                if (item.category != 'select' && item.category != 'judge') {
                    item.questions.map((q, i) => {
                        if (q.category != 'select' && q.category != 'judge') {
                            if (sections[index].questions[i].if_right == undefined) {
                                check_done = 0;
                            } else {
                                item_list.push({
                                    uuid: q.uuid,
                                    answer: '',
                                    if_right: q.if_right
                                })
                                subjective_score += q.if_right == 1 ? q.score * 1 : 0;
                            }
                        }

                    })
                }
            });

            var score = page.data.coach_answer.score * 1 + subjective_score;
            score += '';
            var answer_json = {
                finish: 1,
                picture_list: page.data.coach_answer.picture_list,
                score: score,
                use_time: page.data.coach_answer.use_time,
                item_list: item_list
            };

            var param = {
                coach_id: page.data.coach_id,
                answer_json: JSON.stringify(answer_json)
            }

            app.sendRequest({
                hideLoading: true,
                url: app.api.coach.coach_submit,
                method: 'POST',
                header: {
                    'token': wx.getStorageSync("access_token"),
                    'content-type': 'application/x-www-form-urlencoded'
                },
                data: param,
                success: function (res) {
                    Toast({
                        message: '提交成功！',
                        onClose: function () {
                            wx.redirectTo({
                                url: '../coach_result/coach_result?id=' + page.data.coach_id
                            })
                        }
                    });

                }
            })
        }

        /*app.sendRequest({
            url: app.api.coach.coach_submit,
            method: 'POST',
            header: {
                'token': wx.getStorageSync("access_token"),
                'content-type': 'application/x-www-form-urlencoded'
            },
            data: param,
            success: function (res) {
                console.log(res)
                Toast('提交成功！');
                app.setPageTitle('自批主观题');
                page.setData({
                    coach_answer: {
                        item_list: item_list,
                        use_time: page.data.timeCounter + '',
                        score: objective_score,
                        picture_list: page.data.picture_list
                    },
                    check_mode: 1
                })
            }
        })*/

    },
    //html转wxml处理
    processHtml: function () {
        var page = this;
        var sections = page.data.sections;
        var stemArr = [];
        var analysisArr = [];

        //获取题干解析html总请求数
        var body_url_cnt = 0, body_url_load_cnt = 0;
        var analysis_url_cnt = 0, analysis_url_load_cnt = 0;
        sections.map((s) => {
            s.questions.map((q) => {
                if (q.bodyUrl != undefined && q.bodyUrl.length > 0) {
                    body_url_cnt++;
                }
                if (q.analysisUrl != undefined && q.analysisUrl.length > 0) {
                    analysis_url_cnt++;
                }
            })
        })

        sections.map((item, i) => {
            item.questions.map((q, k) => {

                //获取题干&解析的html内容
                if (q.bodyUrl != undefined && q.bodyUrl.length > 0) {
                    util.get(page.data.downloadUrl + '/' + q.bodyUrl).then(function (res) {
                        body_url_load_cnt++;
                        sections[i].questions[k].body = res.data.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
                        if (body_url_load_cnt == body_url_cnt) {
                            page.setData({
                                sections: sections
                            })
                        }
                    })
                } else {
                    sections[i].questions[k].body = q.body.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
                }
                if (q.analysisUrl != undefined && q.analysisUrl.length > 0) {
                    util.get(page.data.downloadUrl + '/' + q.analysisUrl).then(function (res) {
                        analysis_url_load_cnt++;
                        sections[i].questions[k].analysis = res.data.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
                        if (analysis_url_load_cnt == analysis_url_cnt) {
                            page.setData({
                                sections: sections
                            })
                        }
                    })
                } else {
                    sections[i].questions[k].analysis = q.analysis.replace(/\<img/gi, '<img style="max-width:100%;height:auto"');
                }
                //获取题干&解析的html内容

                //-----题干、解析html转wxml-----
                /*if (q.body.length > 0) {
                    stemArr[q.order - 1] = q.body;
                } else {
                    util.get(page.data.downloadUrl + '/' + q.bodyUrl).then(function (res) {
                        body_url_load_cnt++;
                        stemArr[q.order - 1] = res.data;
                    })
                }

                if (q.analysis.length > 0) {
                    analysisArr[q.order - 1] = q.analysis;
                } else {
                    util.get(page.data.downloadUrl + '/' + q.analysisUrl).then(function (res) {
                        analysis_url_load_cnt++;
                        analysisArr[q.order - 1] = res.data;
                    })
                }

                WxParse.wxParse('stem' + (q.order - 1), 'html', stemArr[(q.order - 1)], page);
                WxParse.wxParse('analysis' + (q.order - 1), 'html', analysisArr[(q.order - 1)], page);

                if (body_url_load_cnt == body_url_cnt) {
                    WxParse.wxParseTemArray("stemTemArray", 'stem', stemArr.length, page);
                }
                if (analysis_url_load_cnt == analysis_url_cnt) {
                    WxParse.wxParseTemArray("analysisTemArray", 'analysis', analysisArr.length, page);
                }*/
                //-----题干、解析html转wxml-----
            })
        });
        page.setData({
            sections: sections
        })
  },
  startSetInter: function(){
    var that = this;
    that.data.setInter = setInterval(
        function () {
          var numVal = that.data.num + 1;

          var use_time = numVal,
              seconds = 0,
              minutes = 0,
              hours = 0;

          seconds = Math.floor(use_time % 60);
          minutes = Math.floor(use_time / 60);
          hours = Math.floor(use_time / 3600);

          if (seconds < 10) {
            seconds = '0' + seconds;
          }
          if (minutes < 10) {
            minutes = '0' + minutes;
          }
          if (hours < 10) {
            hours = '0' + hours;
          }

          var txt = hours + ':' + minutes + ':' + seconds;

          that.setData({
            num: numVal,
            timeCounter: txt
          });
        }
        , 1000);
  },
  endSetInter: function(){
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
  },
  //开始学习
  startLearn: function (e) {
    var page = this;
    page.setData({
      show_status: !page.data.show_status
    })
    page.startSetInter();
  },
  //画面数据格式预处理
  preProcessData: function () {
    var page = this;
    var sections = page.data.sections;

    // 客观题数量
    var objective_question_num = 0;

    var last_uuid = 0;
    sections.map((s,s_i) => {
      sections[s_i].questions.map((q,i) => {
        //多选题的情况,答案转数组
        if (sections[s_i].questions[i].category == 'select' && sections[s_i].questions[i].correct.length > 1) {
          sections[s_i].questions[i].correct = sections[s_i].questions[i].correct.split('');
          if (sections[s_i].questions[i].student_answer != undefined) {
            sections[s_i].questions[i].student_answer = sections[s_i].questions[i].student_answer.split('');
          }
        }

        if (q.category == 'select' || q.category == 'judge') {
          objective_question_num += 1;
        }
        last_uuid = q.uuid;
      });
    });

    page.setData({
      last_uuid: last_uuid
    })

    //判断是否有主观题
    var has_subjective_question = 0;
    if (objective_question_num == page.data.questionCount) {
      has_subjective_question = 0;
    } else {
      has_subjective_question = 1;
    }
    //判断是否有主观题

    page.setData({
      has_subjective_question: has_subjective_question,
      sections: sections
    })
  },
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFiles = res.tempFiles;
        that.setData({
          files: that.data.files.concat(tempFiles[0].path)
        });

        that.uploadQiniu(tempFiles);
      }
    });
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    });
  },
  /**
   * 图片上传七牛云
   */
  uploadQiniu: function (tempFilePaths) {
    var that = this;
    wx.uploadFile({
      // url: app.api.xh.uploadUrl,
      url: app.api.xh.uploadDomain,
      name: 'file',
      filePath: tempFilePaths[0].path,
      header: {
          "Content-Type": "multipart/form-data",
          "token": wx.getStorageSync("access_token")
      },
      // formData: {
      //   token: that.data.uploadToken
      // },
      success: function (res) {
        console.log(res);
        let data = JSON.parse(res.data);
        var picture_list = that.data.picture_list;
        // picture_list.push({url: data.key, name: data.key, size: tempFilePaths[0].size});
        picture_list.push(data.data.url);
        that.setData({
          picture_list: picture_list
        });
        !that.data.show_status && that.startLearn();
      },
      fail: function (res) {
        console.log(res)
      }
    });
  },
  toggleCatalog: function (e) {
    var page = this;
    var expand_status = e.currentTarget.dataset.expand;
    var id = e.currentTarget.dataset.id,
        sections = page.data.sections;

    sections.map((item,s_index) => {
      sections[s_index].questions.map((q,q_index) => {
        if (sections[s_index].questions[q_index].uuid == id) {
          sections[s_index].questions[q_index].expand = !expand_status;
        }
      })
    });

    page.setData({
      sections: sections
    });
  },
  //单选题处理
  onChange(e) {
    var page = this,
        select_qid = e.currentTarget.dataset.id,
        select_option = e.detail,
        sections = page.data.sections,
        doneQCount = 0;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

    sections.map((item, index) => {
      sections[index].questions.map((q, i) => {
        if (sections[index].questions[i].uuid == select_qid) {
          sections[index].questions[i].student_answer = select_options[select_option];
        }
        if (sections[index].questions[i].student_answer != undefined) {
          doneQCount++;
        }
      })
    });

    page.setData({
      doneQCount: doneQCount,
      sections: sections
    });
    !page.data.show_status && page.startLearn();
  },
  //判断题处理
  onPDChange(e) {
    var page = this,
        select_qid = e.currentTarget.dataset.id,
        select_option = e.detail,
        // questions = page.data.questions,
        sections = page.data.sections,
        doneQCount = 0;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

    sections.map((item, index) => {
      sections[index].questions.map((q, i) => {
        sections[index].questions[i]
        if (sections[index].questions[i].uuid == select_qid) {
          sections[index].questions[i].student_answer = select_option;
        }
        if (sections[index].questions[i].student_answer != undefined) {
          doneQCount++;
        }
      })
    });

    page.setData({
      doneQCount: doneQCount,
      sections: sections
    });
    !page.data.show_status && page.startLearn();
  },
  //多选题处理
  onCBChange(e) {
    var page = this,
        select_qid = e.currentTarget.dataset.id,
        // questions = page.data.questions,
        sections = page.data.sections,
        doneQCount = 0;

    //已提交的情况间接实现只读效果
    if (page.data.if_commit == 2) {
      return;
    }

    sections.map((item, index) => {
      sections[index].questions.map((q, i) => {
        if (sections[index].questions[i].uuid == select_qid) {
          sections[index].questions[i].student_answer = e.detail;
        }
        if (sections[index].questions[i].student_answer != undefined) {
          doneQCount++;
        }
      })
    });

    page.setData({
      doneQCount: doneQCount,
      sections: sections
    });
  },
  doJudge: function (e) {
    var page = this,
        select_qid = e.currentTarget.dataset.id,
        if_right = e.currentTarget.dataset.ifright,
        sections = page.data.sections;

    sections.map((item, index) => {
      sections[index].questions.map((q, i) => {
        if (sections[index].questions[i].uuid == select_qid) {
          sections[index].questions[i].if_right = parseInt(if_right);
          return false;
        }
      })
    });
    page.setData({
      sections: sections
    });
  },
  //提交自批结果
  submitCheckSelf: function () {
      var page = this,
          sections = page.data.sections,
          item_list = page.data.coach_answer.item_list;

      var check_done = 1;//判断是否自批完毕

      var subjective_score = 0;//主观题分数
      sections.map((item, index) => {
          if (item.category != 'select' && item.category != 'judge') {
              item.questions.map((q, i) => {
                  if (q.category != 'select' && q.category != 'judge') {
                      if (sections[index].questions[i].if_right == undefined) {
                          check_done = 0;
                      } else {
                          item_list.push({
                              uuid: q.uuid,
                              answer: '',
                              if_right: q.if_right
                          })
                          subjective_score += q.if_right == 1 ? q.score * 1 : 0;
                      }
                  }

              })
          }
      });

      if (check_done == 0) {
          Dialog.alert({
              message: '请先完成所有主观题的自批。'
          });
          return false;
      } else {
          var score = page.data.coach_answer.score * 1 + subjective_score;
          score += '';
          var answer_json = {
              finish: 1,
              picture_list: page.data.coach_answer.picture_list,
              score: score,
              use_time: page.data.coach_answer.use_time,
              item_list: item_list
          };

          var param = {
              coach_id: page.data.coach_id,
              answer_json: JSON.stringify(answer_json)
          }

          app.sendRequest({
              hideLoading: true,
              url: app.api.coach.coach_submit,
              method: 'POST',
              header: {
                  'token': wx.getStorageSync("access_token"),
                  'content-type': 'application/x-www-form-urlencoded'
              },
              data: param,
              success: function (res) {
                  Toast({
                          message: '提交成功！',
                          onClose: function () {
                              wx.redirectTo({
                                  url: '../coach_result/coach_result?id=' + page.data.coach_id
                              })
                          }
                      });

              }
          })
      }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var page = this;
    var coach_id = options.id == undefined ? 85 : options.id;
    page.setData({
      coach_id: coach_id
    })
    // var options = {
    //   region: 'SCN', // 华北区
    //   uptokenURL: app.api.xh.upTokenUrl,
    //   domain: app.api.xh.domain,
    //   shouldUseQiniuFileName: false
    // };
    //   xhUploader.init(options);

    // app.sendRequest({
    //   url: app.api.xh.upTokenUrl,
    //   success: res => {
    //     page.setData({
    //       uploadToken: res.token
    //     })
    //   }
    // });
      app.sendRequest({
          url: app.api.coach.coach_info,
          data: {coach_id: coach_id},
          success: res => {
              var page_title = res.data.name;
              app.setPageTitle(page_title);
              app.sendRequest({
                  url: page.data.downloadUrl + '/' + res.data.question_url,
                  success: res => {
                      console.log(res)
                      page.setData({
                          sections: res.sections,
                          questionCount: res.questionCount
                      })
                      page.preProcessData();
                      page.processHtml();
                      page.setData({
                          showSkeleton: false
                      });
                  }
              })

          }
      })
      app.sendRequest({
          url: app.api.coach.coach_answer,
          data: {coach_id: coach_id},
          success: res => {
              var answer = res.data;
              if (answer != null && answer.finish != undefined) {
                  app.setPageTitle('自批主观题');
                  page.setData({
                      check_mode: 1,
                      coach_answer: answer,
                      if_commit: 2
                  })
              }


          }
      })


    //
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that =this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})